/*
 * @Description: 添加字段显隐规则-第二个Drawer
 * @Autor: gufuyan
 * @Date: 2021-11-15 11:26:31
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-12-03 16:40:35
 * @lastModifiedContent:
 */

import React, { useState, useEffect } from 'react';
import { Drawer, Button, Select, message, TreeSelect } from 'antd';
import { useModel } from 'umi';
import { intl } from '../FormAttributes';
import EditableField from './EditableField';
import type { DataSourceType, IAddShowFieldProps, FieldNameTree } from './data';
import styles from './index.less';

const { Option } = Select;

const AddFieldRule: React.FC<IAddShowFieldProps> = (props) => {
  // 配置全局信息
  const drag = useModel('drag');
  // 显示以下字段的下拉选项
  const [fieldOptions, setFieldOptions] = useState<FieldNameTree[]>([]);
  const [fieldNameObj, setFieldNameObj] = useState<any>({});
  // 配置的显隐规则列表数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  // 是否正正编辑状态
  const [isEdit, setIsEdit] = useState(false);

  const [showField, setShowField] = useState<React.Key[]>();
  const [rel, setRel] = useState<string>('and');

  useEffect(() => {
    // 初始化根据layout设置显示字段的下拉选项
    const tree: FieldNameTree[] = [];
    const obj: any = {};
    drag.config?.contentItem?.forEach(
      (el: {
        name: string;
        id: string | number;
        title: string;
        field: string;
        props: { options: any };
        children: string | any[];
      }) => {
        if (!['placeBlock', 'splitLine'].includes(el.name)) {
          const data: any = {
            value: el.id,
            title: el.title,
            type: el.name,
            fieldName: el.field,
            fieldOptions: el.props?.options,
            disabled: props?.showFields?.has(el.id) ? true : false,
          };
          obj[el.id] = { ...data };
          if (el.children && el.children.length) {
            data.children = [];
            el.children[0].forEach(
              (childEl: {
                id: string;
                title: string;
                name: string;
                field: string;
                props: { options: any };
              }) => {
                const cData = {
                  value: childEl.id,
                  title: childEl.title,
                  type: childEl.name,
                  fieldName: childEl.field,
                  fieldOptions: childEl.props?.options,
                  disabled: props?.showFields?.has(childEl.id) ? true : false,
                };
                obj[childEl.id] = { ...cData };
                data.children.push(cData);
              },
            );
          }
          tree.push(data);
        }
      },
    );
    setFieldOptions(tree);
    setFieldNameObj(obj);
  }, [drag, props?.showFields]);

  useEffect(() => {
    // 新增
    if (!props.visible) return;
    if (props.editType === 'add') {
      setDataSource([]);
      setRel('and');
      setShowField([]);
      return;
    }
    // 编辑
    const data = props.editRule;
    if (data.filter) {
      const newDataSource: DataSourceType[] = [];
      data.filter.cond.forEach(
        (el: { value: string; field: string; text: string; method: string }) => {
          newDataSource.push({
            id: Math.floor(Math.random() * 100000000),
            checkValue: el.value,
            fieldName: el.field,
            fieldNameText: el.text,
            rule: el.method,
          });
        },
      );
      setDataSource(newDataSource);
      setRel(data.filter.rel);
      setShowField(data.fields);
    }
  }, [props.editRule, props.editType, props.visible]);

  /**
   * 关闭弹出框，提交数据，校验，数据处理
   */
  const onSubmit = () => {
    if (!dataSource.length || isEdit) {
      message.error('请配置显隐规则条件并且保存再提交！');
      return;
    }
    if (!showField?.length) {
      message.error('请选择需要显示的字段再提交！');
      return;
    }

    const cond: {
      type: string;
      method: string | undefined;
      field: string | undefined;
      value: string;
      text: any;
    }[] = [];

    dataSource.forEach((el) => {
      cond.push({
        type: fieldNameObj[el.fieldName || '']?.type, // fieldOptions.filter((item) => item.value === el.fieldName)[0].type,
        method: el.rule,
        field: el.fieldName,
        value: el.checkValue,
        text: el.fieldNameText,
      });
    });

    const newFieldShowRules = props.currentFieldRules;
    if (props.editType === 'add') {
      newFieldShowRules.push({
        filter: {
          cond: cond,
          rel: rel,
        },
        fields: showField,
        tempId: new Date().getTime(),
      });
    } else {
      newFieldShowRules.forEach((item: any) => {
        if (item.tempId === props.editRule.tempId) {
          item.fields = showField;
          item.filter = {
            cond: cond,
            rel: rel,
          };
        }
      });
    }
    props.onClose(newFieldShowRules);
  };

  return (
    <Drawer
      title={props.editType === 'add' ? intl('drag.exp.imp.add') : intl('drag.exp.imp.edit')}
      key="childDrawer"
      placement="left"
      width={900}
      closable={false}
      onClose={() => props.onClose}
      visible={props.visible}
      className={styles.expImpBox}
      footer={
        <div className={styles.footer}>
          <Button className={styles.btn} onClick={() => props.onClose()}>
            {intl('drag.cancel')}
          </Button>
          <Button className={styles.btn} type="primary" onClick={onSubmit}>
            {intl('drag.add')}
          </Button>
        </div>
      }
    >
      {/* 满足条件 */}
      <div className={styles.title}>
        <span>{intl('drag.exp.imp.satisfy')}</span>
        <Select
          size="small"
          className={styles.select}
          value={rel}
          onChange={(value) => setRel(value)}
        >
          <Option key="and" value="and">
            {intl(`drag.exp.imp.all`)}
          </Option>
          <Option key="or" value="or">
            {intl(`drag.exp.imp.either`)}
          </Option>
        </Select>
        <span>{intl('drag.exp.imp.condition')}</span>
      </div>

      {/* 添加规则表格 */}
      <EditableField
        dataSource={dataSource}
        setDataSource={(value) => setDataSource(value)}
        setIsEdit={(value) => {
          setIsEdit(value);
        }}
      />

      {/* 显示以下字段：根据规则需显示的字段 */}
      <div className={styles.title}>{intl('drag.exp.imp.show')}</div>
      <TreeSelect
        showSearch
        allowClear
        multiple
        treeDefaultExpandAll
        style={{ width: '100%' }}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="请选择"
        treeData={fieldOptions}
        value={showField}
        onChange={(keys: React.Key[]) => {
          setShowField(keys);
        }}
      />
    </Drawer>
  );
};

export default AddFieldRule;
